package com.ruoyi.transfers.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.goods.controller.TGoodsInfoController;
import com.ruoyi.goods.service.ITGoodsInfoService;
import com.ruoyi.transfers.domain.WGoodsTransferInfo;
import com.ruoyi.transfers.service.IWGoodsTransferInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.transfers.domain.WGoodsTransferRel;
import com.ruoyi.transfers.service.IWGoodsTransferRelService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 货转关联Controller
 * 
 * @author ruoyi
 * @date 2023-11-15
 */
@RestController
@RequestMapping("/transfers/relate")
public class WGoodsTransferRelController extends BaseController
{
    @Autowired
    private IWGoodsTransferRelService wGoodsTransferRelService;

    @Autowired
    private IWGoodsTransferInfoService wGoodsTransferInfoService;

    @Autowired
    private ITGoodsInfoService tGoodsInfoService;


    private static Logger logger = LoggerFactory.getLogger(WGoodsTransferRelController.class);
    /**
     * 查询货转关联列表
     */
    @PreAuthorize("@ss.hasPermi('transfers:relate:list')")
    @GetMapping("/list")
    public TableDataInfo list(WGoodsTransferRel wGoodsTransferRel)
    {
        startPage();
        List<WGoodsTransferRel> list = wGoodsTransferRelService.selectWGoodsTransferRelList(wGoodsTransferRel);
        return getDataTable(list);
    }

    /**
     * 导出货转关联列表
     */
    @PreAuthorize("@ss.hasPermi('transfers:relate:export')")
    @Log(title = "货转关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WGoodsTransferRel wGoodsTransferRel)
    {
        List<WGoodsTransferRel> list = wGoodsTransferRelService.selectWGoodsTransferRelList(wGoodsTransferRel);
        ExcelUtil<WGoodsTransferRel> util = new ExcelUtil<WGoodsTransferRel>(WGoodsTransferRel.class);
        util.exportExcel(response, list, "货转关联数据");
    }

    /**
     * 获取货转关联详细信息
     */
    @PreAuthorize("@ss.hasPermi('transfers:relate:query')")
    @GetMapping(value = "/{goodsTransferId}")
    public AjaxResult getInfo(@PathVariable("goodsTransferId") Long goodsTransferId)
    {
        return success(wGoodsTransferRelService.selectWGoodsTransferRelByGoodsTransferId(goodsTransferId));
    }

    /**
     * 新增货转关联
     */
    @PreAuthorize("@ss.hasPermi('transfers:relate:add')")
    @Log(title = "货转关联", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WGoodsTransferRel wGoodsTransferRel)
    {
        //wGoodsTransferRel.setCreateBy(getNickName());
        return toAjax(wGoodsTransferRelService.insertWGoodsTransferRel(wGoodsTransferRel));
    }

    /**
     * 修改货转关联
     */
    @PreAuthorize("@ss.hasPermi('transfers:relate:edit')")
    @Log(title = "货转关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WGoodsTransferRel wGoodsTransferRel)
    {
        //wGoodsTransferRel.setUpdateBy(getNickName());
        return toAjax(wGoodsTransferRelService.updateWGoodsTransferRel(wGoodsTransferRel));
    }

    /**
     * 删除货转关联
     */
    @PreAuthorize("@ss.hasPermi('transfers:relate:remove')")
    @Log(title = "货转关联", businessType = BusinessType.DELETE)
	@DeleteMapping("/{goodsTransferIds}")
    public AjaxResult remove(@PathVariable Long[] goodsTransferIds)
    {
        return toAjax(wGoodsTransferRelService.deleteWGoodsTransferRelByGoodsTransferIds(goodsTransferIds));
    }

    /**
     * 新增货转关联
     */
//    @PreAuthorize("@ss.hasPermi('transfers:relate:add')")
    @Log(title = "货转关联", businessType = BusinessType.INSERT)
    @PostMapping("/ext/{goodsIds}/{goodsTransferId}")
    public AjaxResult addExt(@PathVariable List<Long> goodsIds, @PathVariable Long goodsTransferId)
    {
        Integer rtn = 0;
        WGoodsTransferInfo goodsTransferInfo = wGoodsTransferInfoService.selectWGoodsTransferInfoByGoodsTransferId(goodsTransferId);
        if(StringUtils.isNull(goodsTransferInfo)) {
            return error("当前作业，已删除，货转加货失败！");
        } else if(goodsTransferInfo.getGoodsTransferStatus().equals("1")) {
            return error("当前作业，已审核通过，加货失败！");
        }
        List<WGoodsTransferInfo> listX = wGoodsTransferInfoService.selectWGoodsTransferInfoByGoodsId(goodsIds, goodsTransferId);
        StringBuilder sb = new StringBuilder();
        if(listX.size() > 0) {
            sb.append("部分货物在{");
            for (WGoodsTransferInfo wGoodsTransferInfo : listX){
                sb.append(wGoodsTransferInfo.getGoodsTransferNumber());
                sb.append(", ");
            }
            sb.append("}未审核/已退回，的货转单中");
            return new AjaxResult(500, sb.toString());
        }
//        logger.debug("XXX " + "listX = " + listX);
//        logger.debug("XXX " + "goodsIds = " + goodsIds);
        List<Long> list = wGoodsTransferRelService.selectWGoodsTransferRelExt(goodsIds, goodsTransferId);
//        logger.debug("XXX " + "list = " + list);
        for(Long item : list) {
            goodsIds.remove(item);
        }
//        logger.debug("YYY " + "goodsIds = " + goodsIds);

        if(goodsIds.size() > 0) {
            tGoodsInfoService.updateTGoodsInventoryStatusByGoodsIds(goodsIds, "货转中");
            rtn = wGoodsTransferRelService.insertWGoodsTransferRelExt(goodsIds, goodsTransferId);
            if(rtn > 0)
            {
                rtn = wGoodsTransferInfoService.updateWTransferTotalWeightPieceByGoodsTransferId(goodsTransferId);
                if(rtn == 0)
                {
                    logger.error("XXX edit " + "update Transfer Total Weight Piece error");
                }
            }
            return toAjax(rtn);
        } else {
            return toAjax(true);
        }
//        return toAjax(true);
    }

    /**
     * 删除货转关联
     */
//    @PreAuthorize("@ss.hasPermi('transfers:relate:add')")
    @Log(title = "货转关联", businessType = BusinessType.DELETE)
    @DeleteMapping("/ext/{goodsIds}/{goodsTransferId}")
    public AjaxResult removeExt(@PathVariable List<Long> goodsIds, @PathVariable Long goodsTransferId)
    {
        Integer rtn = 0;
        WGoodsTransferInfo goodsTransferInfo = wGoodsTransferInfoService.selectWGoodsTransferInfoByGoodsTransferId(goodsTransferId);
        if(StringUtils.isNull(goodsTransferInfo)) {
            return error("当前作业，已删除，货转移除失败！");
        } else if(goodsTransferInfo.getGoodsTransferStatus().equals("1")) {
            return error("当前作业，已审核通过，移除失败！");
        }
        tGoodsInfoService.updateTGoodsInventoryStatusByGoodsIds(goodsIds, "已在库");
        rtn = wGoodsTransferRelService.deleteWGoodsTransferRelExt(goodsIds, goodsTransferId);
        if(rtn > 0)
        {
            rtn = wGoodsTransferInfoService.updateWTransferTotalWeightPieceByGoodsTransferId(goodsTransferId);
            if(rtn == 0)
            {
                logger.error("XXX remove " + "update Transfer Total Weight Piece error");
            }
        }
        return toAjax(rtn);
    }

}
